using System;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using AppTableUtils;


public class JsonDataTableConverter
{
// 将JSON字符串转换为DataTable
    public static DataTable JsonToDataTable(string json)
    {
        // 使用 JArray 解析 JSON 数组
        var jsonArray = JArray.Parse(json);
        // 创建一个 DataTable
        var dataTable = new DataTable();

        // 如果 JSON 数组不为空，动态创建 DataTable 的列
        if (jsonArray.Count > 0)
        {
            // 获取 JSON 对象的第一个元素
            var jsonObject = jsonArray[0] as JObject;
            foreach (var property in jsonObject.Properties())
            {
                dataTable.Columns.Add(new DataColumn(property.Name, typeof(string)));
            }

            // 将 JSON 数据填充到 DataTable
            foreach (var item in jsonArray)
            {
                var dataRow = dataTable.NewRow();
                foreach (var property in (item as JObject).Properties())
                {
                    dataRow[property.Name] = property.Value.ToString();
                }
                dataTable.Rows.Add(dataRow);
            }
        }

        return dataTable;
    }

// 将DataTable转换为JSON字符串
    public static string DataTableToJson(DataTable dataTable)
    {
        return JsonConvert.SerializeObject(dataTable, Formatting.Indented);
    }
    
    public static List<Dictionary<string, object>> DataTableToList(DataTable table)
    {
        return table.AsEnumerable()
                    .Select(row => table.Columns.Cast<DataColumn>()
                                             .ToDictionary(column => column.ColumnName, column => row[column]))
                    .ToList();
    }
    
    public static DataTable ListToDataTable(List<Dictionary<string, object>> list)
    {
        DataTable table = new DataTable();

        if (list == null || list.Count == 0)
            return table;

        // 添加列到 DataTable
        foreach (var key in list[0].Keys)
        {
            table.Columns.Add(key);
        }

        // 添加行到 DataTable
        foreach (var dict in list)
        {
            DataRow row = table.NewRow();
            foreach (var kvp in dict)
            {
                row[kvp.Key] = kvp.Value ?? DBNull.Value;
            }
            table.Rows.Add(row);
        }

        return table;
    }

    public static Dictionary<string, object> conv_dc_ls_to_data_dc(List<Dictionary<string, object>> dc_ls, string pk_name=null)
    {
        Dictionary<string, object> data_dc = new Dictionary<string, object>()
        {
            {"pk", pk_name},
            {"data", dc_ls}
        };
        return data_dc;
    }

    public static Dictionary<string, object> conv_dt_to_data_dc(DataTable dt)
    {
        string pk_name = AppTableUtils.TableUtils.get_pk_name_of_dt(dt);
        var dc_ls = DataTableToList(dt);
        var data_dc = conv_dc_ls_to_data_dc(dc_ls, pk_name);
        return data_dc;
    }

    public static DataTable conv_data_dc_to_dt(Dictionary<string, object> data_dc)
    {
        string head_json = JsonConvert.SerializeObject(data_dc);
        var new_data_dc = JsonConvert.DeserializeObject<Dictionary<string, object>>(head_json);
        
        BdPackage.BdUtils.assert(new_data_dc.ContainsKey("data"), "data_dc的keys中没有`data`?");
        var new_dc_ls = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(new_data_dc["data"].ToString());

        BdPackage.BdUtils.assert(new_data_dc.ContainsKey("pk"), "data_dc的keys中没有`pk`?");
        string pk_name = BdUtils.conv_to_string(new_data_dc["pk"]);
        
        var new_dt = ListToDataTable(new_dc_ls);
        if (BdPackage.BdUtils.not_null(pk_name))
            AppTableUtils.TableUtils.set_pk_of_dt(new_dt, pk_name);
        return new_dt;
    }

    public class DataDictUtils
    {
        public static void save_to_json(Dictionary<string, object> data_dc, string f_path)
        {
            // 序列化字典到JSON格式
            string jsonString = JsonConvert.SerializeObject(data_dc, Formatting.Indented);
            // 将JSON字符串写入文件
            // UTF8Encoding utf8NoBom = new UTF8Encoding(false);
            File.WriteAllText(f_path, jsonString, Encoding.UTF8);
        }

        public static Dictionary<string, object> load_data_dc_from_json(string f_path)
        {
            string jsonString = File.ReadAllText(f_path, Encoding.UTF8);
            // 反序列化JSON字符串到字典
            var data_dc = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
            return data_dc;
        }
    }

    public static void save_dt_to_json(DataTable dt, string f_path)
    {
        var data_dc = conv_dt_to_data_dc(dt);
        DataDictUtils.save_to_json(data_dc, f_path);
    }

    public static DataTable load_dt_from_json(string f_path, string pk_name = null)
    {
        var data_dc = DataDictUtils.load_data_dc_from_json(f_path);
        var dt = conv_data_dc_to_dt(data_dc);
        dt.TableName = f_path;
        if (BdPackage.BdUtils.not_null(pk_name))
            TableUtils.set_pk_of_dt(dt, pk_name);
        return dt;
    }
    
    // 测试函数
    public static void Main()
    {
        string relative_path = "test_dt.json";
        string f_path = BdPackage.BdTools.get_static_abs_file_path_on_all_platform(relative_path);
        // string f_path = BdTools.get_static_abs_file_path_on_all_platform(relative_path);
        // BdPackage.BdUtils.join()

        var dt = load_dt_from_json(f_path);
        
        TableUtils.swap_row(dt, 0, 1);
        
        save_dt_to_json(dt, f_path);
        
        // var new_dt = load_dt_from_json(f_path);
        var new_dt = load_dt_from_json(f_path, pk_name: "Age");
        AppTableUtils.TableUtils.show_data_table(new_dt, show_table_name: true);

    }
}